'use client';

import { useState } from 'react';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import { Activity, Trash2, Database, Server, HardDrive, CheckCircle, XCircle, AlertTriangle, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';
import { useRouter } from 'next/navigation';

export default function SystemMaintenancePage() {
  const { user } = useAuthStore();
  const router = useRouter();
  const [cleaning, setCleaning] = useState(false);
  const [checking, setChecking] = useState(false);
  const [cleanResult, setCleanResult] = useState<any>(null);
  const [healthReport, setHealthReport] = useState<any>(null);

  // 权限检查
  if (user?.role !== 'admin') {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <GlassCard className="p-8 text-center">
          <AlertTriangle className="h-16 w-16 text-yellow-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            权限不足
          </h2>
          <p className="text-gray-600 dark:text-white/70 mb-4">
            只有系统管理员才能访问系统维护功能
          </p>
          <GlassButton onClick={() => router.push('/dashboard')} variant="primary">
            返回仪表盘
          </GlassButton>
        </GlassCard>
      </div>
    );
  }

  const handleCleanOrphanVectors = async () => {
    try {
      setCleaning(true);
      setCleanResult(null);
      toast.loading('正在清理孤儿向量...', { id: 'clean' });

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/system/clean-orphan-vectors`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
        },
      });

      if (!response.ok) {
        throw new Error('清理失败');
      }

      const result = await response.json();
      setCleanResult(result);

      if (result.total_removed_vectors > 0) {
        toast.success(`清理成功！删除了 ${result.total_removed_vectors} 个孤儿向量`, { id: 'clean' });
      } else {
        toast.success('系统干净，无需清理', { id: 'clean' });
      }
    } catch (error: any) {
      console.error('清理失败:', error);
      toast.error('清理失败: ' + (error.message || '未知错误'), { id: 'clean' });
    } finally {
      setCleaning(false);
    }
  };

  const handleHealthCheck = async () => {
    try {
      setChecking(true);
      setHealthReport(null);
      toast.loading('正在检查系统健康状态...', { id: 'health' });

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/system/health-check`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
        },
      });

      if (!response.ok) {
        throw new Error('健康检查失败');
      }

      const result = await response.json();
      setHealthReport(result.report);
      toast.success('健康检查完成', { id: 'health' });
    } catch (error: any) {
      console.error('健康检查失败:', error);
      toast.error('健康检查失败: ' + (error.message || '未知错误'), { id: 'health' });
    } finally {
      setChecking(false);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy':
        return <CheckCircle className="h-6 w-6 text-green-500" />;
      case 'warning':
        return <AlertTriangle className="h-6 w-6 text-yellow-500" />;
      case 'error':
        return <XCircle className="h-6 w-6 text-red-500" />;
      default:
        return <Loader2 className="h-6 w-6 text-gray-400 animate-spin" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'text-green-600 dark:text-green-400';
      case 'warning':
        return 'text-yellow-600 dark:text-yellow-400';
      case 'error':
        return 'text-red-600 dark:text-red-400';
      default:
        return 'text-gray-600 dark:text-gray-400';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
          系统维护
        </h1>
      </div>

      {/* 维护操作卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 清理孤儿向量 */}
        <GlassCard className="p-6">
          <div className="flex items-start gap-4 mb-4">
            <div className="p-3 rounded-lg bg-red-100 dark:bg-red-500/20">
              <Trash2 className="h-8 w-8 text-red-600 dark:text-red-400" />
            </div>
            <div className="flex-1">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
                清理孤儿向量
              </h3>
              <p className="text-sm text-gray-600 dark:text-white/70 mb-4">
                清理已删除文档遗留的向量数据，释放存储空间，保持向量库干净整洁
              </p>
            </div>
          </div>
          
          <GlassButton
            onClick={handleCleanOrphanVectors}
            loading={cleaning}
            disabled={cleaning}
            variant="primary"
            className="w-full"
          >
            {cleaning ? '清理中...' : '开始清理'}
          </GlassButton>

          {/* 清理结果 */}
          {cleanResult && (
            <div className="mt-4 p-4 rounded-lg bg-blue-50 dark:bg-blue-500/10">
              <div className="text-sm space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-white/70">处理知识库数:</span>
                  <span className="font-medium text-gray-900 dark:text-white">{cleanResult.total_kb_count}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-white/70">清理知识库数:</span>
                  <span className="font-medium text-gray-900 dark:text-white">{cleanResult.cleaned_kb_count}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-white/70">删除向量数:</span>
                  <span className="font-medium text-red-600 dark:text-red-400">{cleanResult.total_removed_vectors}</span>
                </div>
              </div>
            </div>
          )}
        </GlassCard>

        {/* 系统健康检查 */}
        <GlassCard className="p-6">
          <div className="flex items-start gap-4 mb-4">
            <div className="p-3 rounded-lg bg-green-100 dark:bg-green-500/20">
              <Activity className="h-8 w-8 text-green-600 dark:text-green-400" />
            </div>
            <div className="flex-1">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
                系统健康检查
              </h3>
              <p className="text-sm text-gray-600 dark:text-white/70 mb-4">
                检查数据库、向量库、Ollama服务和存储空间的健康状态
              </p>
            </div>
          </div>
          
          <GlassButton
            onClick={handleHealthCheck}
            loading={checking}
            disabled={checking}
            variant="primary"
            className="w-full"
          >
            {checking ? '检查中...' : '开始检查'}
          </GlassButton>
        </GlassCard>
      </div>

      {/* 健康检查报告 */}
      {healthReport && (
        <GlassCard className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-6">
            健康检查报告
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 数据库 */}
            <div className="p-4 rounded-lg bg-white/40 dark:bg-white/5">
              <div className="flex items-center gap-3 mb-3">
                {getStatusIcon(healthReport.database?.status)}
                <div>
                  <h3 className="font-bold text-gray-900 dark:text-white">数据库</h3>
                  <p className={`text-sm ${getStatusColor(healthReport.database?.status)}`}>
                    {healthReport.database?.status === 'healthy' ? '正常' : healthReport.database?.status === 'warning' ? '警告' : '错误'}
                  </p>
                </div>
              </div>
              {healthReport.database?.details && (
                <div className="text-sm space-y-1 text-gray-600 dark:text-white/70">
                  {healthReport.database.details.total_documents !== undefined && (
                    <div>文档总数: {healthReport.database.details.total_documents}</div>
                  )}
                  {healthReport.database.details.vectorized_documents !== undefined && (
                    <div>已向量化: {healthReport.database.details.vectorized_documents}</div>
                  )}
                </div>
              )}
            </div>

            {/* 向量库 */}
            <div className="p-4 rounded-lg bg-white/40 dark:bg-white/5">
              <div className="flex items-center gap-3 mb-3">
                {getStatusIcon(healthReport.vectors?.status)}
                <div>
                  <h3 className="font-bold text-gray-900 dark:text-white">向量库</h3>
                  <p className={`text-sm ${getStatusColor(healthReport.vectors?.status)}`}>
                    {healthReport.vectors?.status === 'healthy' ? '正常' : healthReport.vectors?.status === 'warning' ? '警告' : '错误'}
                  </p>
                </div>
              </div>
              {healthReport.vectors?.details && (
                <div className="text-sm space-y-1 text-gray-600 dark:text-white/70">
                  {healthReport.vectors.details.knowledge_base_count !== undefined && (
                    <div>知识库数: {healthReport.vectors.details.knowledge_base_count}</div>
                  )}
                  {healthReport.vectors.details.total_vectors !== undefined && (
                    <div>向量总数: {healthReport.vectors.details.total_vectors}</div>
                  )}
                </div>
              )}
            </div>

            {/* Ollama服务 */}
            <div className="p-4 rounded-lg bg-white/40 dark:bg-white/5">
              <div className="flex items-center gap-3 mb-3">
                {getStatusIcon(healthReport.ollama?.status)}
                <div>
                  <h3 className="font-bold text-gray-900 dark:text-white">Ollama服务</h3>
                  <p className={`text-sm ${getStatusColor(healthReport.ollama?.status)}`}>
                    {healthReport.ollama?.status === 'healthy' ? '正常' : healthReport.ollama?.status === 'warning' ? '警告' : '错误'}
                  </p>
                </div>
              </div>
              {healthReport.ollama?.details && (
                <div className="text-sm space-y-1 text-gray-600 dark:text-white/70">
                  {healthReport.ollama.details.models_count !== undefined && (
                    <div>模型数量: {healthReport.ollama.details.models_count}</div>
                  )}
                </div>
              )}
            </div>

            {/* 存储空间 */}
            <div className="p-4 rounded-lg bg-white/40 dark:bg-white/5">
              <div className="flex items-center gap-3 mb-3">
                {getStatusIcon(healthReport.storage?.status)}
                <div>
                  <h3 className="font-bold text-gray-900 dark:text-white">存储空间</h3>
                  <p className={`text-sm ${getStatusColor(healthReport.storage?.status)}`}>
                    {healthReport.storage?.status === 'healthy' ? '充足' : healthReport.storage?.status === 'warning' ? '告警' : '错误'}
                  </p>
                </div>
              </div>
              {healthReport.storage?.details && (
                <div className="text-sm space-y-1 text-gray-600 dark:text-white/70">
                  {healthReport.storage.details.total_gb && (
                    <div>总容量: {healthReport.storage.details.total_gb} GB</div>
                  )}
                  {healthReport.storage.details.free_gb && (
                    <div>剩余: {healthReport.storage.details.free_gb} GB</div>
                  )}
                  {healthReport.storage.details.usage_percent && (
                    <div>使用率: {healthReport.storage.details.usage_percent}%</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </GlassCard>
      )}
    </div>
  );
}

